import React, { useState, useRef, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './zhibo.module.css';

// WebRTC配置
const rtcConfig = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },
    { urls: 'stun:stun1.l.google.com:19302' },
    { urls: 'stun:stun2.l.google.com:19302' },
    { urls: 'stun:stun3.l.google.com:19302' },
    { urls: 'stun:stun4.l.google.com:19302' },
    // 添加免费TURN服务器(如果需要NAT穿透)
    {
      urls: 'turn:numb.viagenie.ca',
      username: 'webrtc@live.com',
      credential: 'muazkh'
    }
  ]
};

// 下拉菜单组件
const DropdownMenu = ({ title, children, isOpen, onToggle }) => {
  return (
    <div className={styles.dropdownMenu}>
      <button 
        className={styles.dropdownToggle}
        onClick={onToggle}
      >
        {title} {isOpen ? '▼' : '▶'}
      </button>
      {isOpen && (
        <div className={styles.dropdownContent}>
          {children}
        </div>
      )}
    </div>
  );
};

// 直播发送端组件
const StreamSender = ({ roomId = 'live-room-001', onViewerCountChange }) => {
  const navigate = useNavigate();
  
  // 返回首页函数
  const goToHome = () => {
    navigate('/');
  };
  const [stream, setStream] = useState(null);
  const [isStreaming, setIsStreaming] = useState(false);
  const [viewerCount, setViewerCount] = useState(0);
  const [error, setError] = useState(null);
  const [connectionStatus, setConnectionStatus] = useState('disconnected');
  const [mediaInfo, setMediaInfo] = useState('');
  const [browserSupport, setBrowserSupport] = useState({
    mediaDevices: false,
    getUserMedia: false,
    getDisplayMedia: false
  });
  
  // 下拉菜单状态
  const [openMenus, setOpenMenus] = useState({
    stream: true,    // 默认展开直播控制
    danmaku: false,
    checkin: false,
    vote: false
  });
  
  const videoRef = useRef(null);
  const wsRef = useRef(null);
  const peersRef = useRef(new Map());
  const streamRef = useRef(null); // 添加一个ref来保存stream
  const previewRef = useRef(null); // 新增
  const [cameraStream, setCameraStream] = useState(null); // 新增摄像头流
  const [pipPos, setPipPos] = useState({ left: 20, top: 20 }); // 小窗口位置
  const [dragging, setDragging] = useState(false);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [danmakuMessages, setDanmakuMessages] = useState([]); // 弹幕消息列表
  const [danmakuEnabled, setDanmakuEnabled] = useState(true); // 弹幕开关
  const [trackOccupancy, setTrackOccupancy] = useState(new Array(8).fill(0)); // 轨道占用时间
  const cameraVideoRef = useRef(null); // 摄像头video
  
  // 弹幕画中画相关状态
  const [danmakuPipPos, setDanmakuPipPos] = useState({ left: 20, top: 200 }); // 弹幕小窗口位置
  const [danmakuDragging, setDanmakuDragging] = useState(false);
  const [danmakuDragOffset, setDanmakuDragOffset] = useState({ x: 0, y: 0 });
  const [showDanmakuPip, setShowDanmakuPip] = useState(true); // 是否显示弹幕画中画

  // 签到相关状态
  const [checkInCount, setCheckInCount] = useState(0); // 签到人数
  const [checkInUsers, setCheckInUsers] = useState(new Set()); // 签到用户列表
  const [showCheckInPip, setShowCheckInPip] = useState(true); // 是否显示签到窗口

  // 投票系统相关状态
  const [voteData, setVoteData] = useState({
    isActive: false,
    question: '',
    options: [],
    results: {},
    totalVotes: 0,
    voters: new Set()
  });
  const [showVotePip, setShowVotePip] = useState(true); // 是否显示投票窗口
  const [votePipPos, setVotePipPos] = useState({ left: 20, top: 420 }); // 投票窗口位置
  const [voteDragging, setVoteDragging] = useState(false);
  const [voteDragOffset, setVoteDragOffset] = useState({ x: 0, y: 0 });

  // 切换下拉菜单
  const toggleMenu = (menuName) => {
    console.log('切换菜单:', menuName, '当前状态:', openMenus[menuName]);
    setOpenMenus(prev => {
      const newState = {
        ...prev,
        [menuName]: !prev[menuName]
      };
      console.log('新状态:', newState);
      return newState;
    });
  };

  // WebSocket连接
  const connectWebSocket = useCallback(() => {
    if (wsRef.current?.readyState === WebSocket.OPEN) return;
    
    try {
      console.log('直播端: 连接WebSocket服务器...');
      // 使用当前页面的主机地址，而不是硬编码localhost
      const wsUrl = `ws://${window.location.hostname}:9000/room/${roomId}`;
      console.log('连接URL:', wsUrl);
      const ws = new WebSocket(wsUrl);
      
      ws.onopen = () => {
        console.log('直播端WebSocket连接成功');
        console.log('WebSocket状态:', ws.readyState);
        setConnectionStatus('connected');
      };
      
      ws.onmessage = async (event) => {
        try {
          const message = JSON.parse(event.data);
          console.log('直播端: 收到消息:', message.type);
          await handleSignalingMessage(message);
        } catch (error) {
          console.error('处理信令消息失败:', error);
        }
      };
      
      ws.onclose = () => {
        console.log('直播端WebSocket连接关闭');
        setConnectionStatus('disconnected');
        // 自动重连
        setTimeout(connectWebSocket, 3000);
      };
      
      ws.onerror = (error) => {
        console.error('直播端WebSocket错误:', error);
        setConnectionStatus('error');
      };
      
      wsRef.current = ws;
    } catch (error) {
      console.error('WebSocket连接失败:', error);
      setError(`WebSocket连接失败: ${error.message}`);
      setTimeout(connectWebSocket, 5000);
    }
  }, [roomId]);

  // 检查浏览器兼容性
  useEffect(() => {
    const checkBrowserSupport = () => {
      const support = {
        mediaDevices: !!navigator.mediaDevices,
        getUserMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
        getDisplayMedia: !!(navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia)
      };
      
      setBrowserSupport(support);
      
      // 检查是否在安全环境下
      const isSecureContext = window.isSecureContext;
      const isLocalhost = location.hostname === 'localhost' || location.hostname === '127.0.0.1';
      const isIPAddress = /^192\.168\.|^10\.|^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(location.hostname);
      
      console.log('安全环境检查:', {
        isSecureContext,
        isLocalhost,
        isIPAddress,
        hostname: location.hostname,
        protocol: location.protocol
      });
      
      if (!support.mediaDevices) {
        setError('浏览器不支持 mediaDevices API，请使用现代浏览器');
      } else if (!support.getDisplayMedia) {
        setError('浏览器不支持屏幕共享功能，请使用Chrome、Firefox或Edge浏览器');
      } else if (!isSecureContext && !isLocalhost && !isIPAddress) {
        setError('媒体API需要HTTPS环境或本地访问，请使用HTTPS或配置浏览器允许不安全来源');
      }
      
      console.log('浏览器兼容性检查:', support);
    };
    
    checkBrowserSupport();
  }, []);

  // 处理信令消息
  const handleSignalingMessage = async (message) => {
    const { type, data, from } = message;
    
    console.log('直播端收到WebSocket消息:', { type, from, dataLength: data ? Object.keys(data).length : 0 });
    
    switch (type) {
      case 'viewer-join':
        console.log('观众加入:', from);
        if (!streamRef.current) {
          console.error('handleSignalingMessage: 没有可用的媒体流，无法处理观众加入');
          return;
        }
        await handleViewerJoin(from);
        break;
      case 'answer':
        console.log('收到answer:', from);
        await handleAnswer(data, from);
        break;
      case 'ice-candidate':
        console.log('收到ICE候选:', from);
        await handleIceCandidate(data, from);
        break;
      case 'viewer-leave':
        console.log('观众离开:', from);
        handleViewerLeave(from);
        break;
      case 'streaming-started':
        console.log('直播已开始确认');
        break;
      case 'danmaku':
        console.log('收到弹幕消息:', data);
        console.log('弹幕消息详情:', {
          content: data?.content,
          sender: data?.sender,
          id: data?.id,
          timestamp: data?.timestamp,
          roomId: data?.roomId
        });
        // 确保弹幕消息有正确的结构
        const danmakuMessage = {
          ...data,
          sender: 'viewer',
          id: data.id || Math.random().toString(36).substr(2, 9)
        };
        console.log('处理后的弹幕消息:', danmakuMessage);
        addDanmakuMessage(danmakuMessage);
        // 广播弹幕给其他观众
        broadcastDanmaku(danmakuMessage);
        break;
      case 'broadcast-danmaku':
        console.log('收到广播弹幕:', data);
        addDanmakuMessage(data);
        break;
      case 'check-in-success':
        console.log('观众签到成功:', data);
        if (data && typeof data.count === 'number') {
          setCheckInCount(data.count);
          if (data.clientId) {
            setCheckInUsers(prev => new Set([...prev, data.clientId]));
          }
        } else {
          console.error('签到成功消息格式错误:', data);
        }
        break;
      case 'check-in-stats':
        console.log('收到签到统计:', data);
        if (data && typeof data.count === 'number' && Array.isArray(data.users)) {
          setCheckInCount(data.count);
          setCheckInUsers(new Set(data.users));
        } else {
          console.error('签到统计消息格式错误:', data);
        }
        break;
      case 'check-in-reset':
        console.log('签到已重置');
        setCheckInCount(0);
        setCheckInUsers(new Set());
        break;
      case 'vote-start':
        console.log('投票开始:', data);
        setVoteData(prev => ({
          ...prev,
          isActive: true,
          question: data.question || '',
          options: data.options || [],
          results: {},
          totalVotes: 0,
          voters: new Set()
        }));
        break;
      case 'vote-end':
        console.log('投票结束:', data);
        setVoteData(prev => ({
          ...prev,
          isActive: false,
          results: data.results || {},
          totalVotes: data.totalVotes || 0
        }));
        break;
      case 'vote-update':
        console.log('投票更新:', data);
        setVoteData(prev => ({
          ...prev,
          results: data.results || {},
          totalVotes: data.totalVotes || 0,
          voters: new Set(data.voters || [])
        }));
        break;
      case 'vote-reset':
        console.log('投票重置');
        setVoteData({
          isActive: false,
          question: '',
          options: [],
          results: {},
          totalVotes: 0,
          voters: new Set()
        });
        break;
      case 'chat':
      case 'message':
      case 'comment':
        console.log('收到聊天消息:', data);
        // 处理其他可能的聊天消息类型
        const chatMessage = {
          ...data,
          sender: 'viewer',
          id: data.id || Math.random().toString(36).substr(2, 9),
          content: data.content || data.message || data.comment || '未知消息'
        };
        console.log('处理后的聊天消息:', chatMessage);
        addDanmakuMessage(chatMessage);
        break;
      case 'error':
        console.error('服务器错误:', data?.message || '未知错误');
        setError(data?.message || '服务器错误');
        break;
      default:
        console.log('未知消息类型:', type);
    }
  };

  // 处理观众加入
  const handleViewerJoin = async (viewerId) => {
    // 使用streamRef而非state中的stream
    const currentStream = streamRef.current;
    console.log('处理观众加入, 流状态:', currentStream ? 'stream存在' : 'stream不存在');
    
    if (!currentStream) {
      console.error('没有可用的媒体流，无法处理观众加入');
      return;
    }
    
    try {
      console.log('为观众创建PeerConnection:', viewerId);
      const peerConnection = new RTCPeerConnection(rtcConfig);
      
      // 添加主屏幕流
      const tracks = currentStream.getTracks();
      console.log(`添加${tracks.length}个主屏幕轨道到PeerConnection`);
      
      tracks.forEach(track => {
        console.log('添加主屏幕轨道到PeerConnection:', track.kind, track.id);
        peerConnection.addTrack(track, currentStream);
      });
      
      // 如果有摄像头流，也添加摄像头轨道
      if (cameraStream) {
        const cameraTracks = cameraStream.getTracks();
        console.log(`添加${cameraTracks.length}个摄像头轨道到PeerConnection`);
        
        cameraTracks.forEach(track => {
          console.log('添加摄像头轨道到PeerConnection:', track.kind, track.id, 'label:', track.label);
          // 为摄像头轨道添加特殊标识
          track.contentHint = 'camera';
          // 使用自定义属性来标识摄像头轨道
          track._isCameraTrack = true;
          peerConnection.addTrack(track, cameraStream);
        });
        
        // 添加调试信息
        console.log('摄像头轨道已添加到PeerConnection，观众应该能看到PIP窗口');
      }
      
      // 处理ICE候选
      peerConnection.onicecandidate = (event) => {
        if (event.candidate && wsRef.current?.readyState === WebSocket.OPEN) {
          console.log('发送ICE候选到观众:', viewerId);
          wsRef.current.send(JSON.stringify({
            type: 'ice-candidate',
            data: event.candidate,
            to: viewerId
          }));
        }
      };
      
      // 监控ICE连接状态
      peerConnection.oniceconnectionstatechange = () => {
        console.log('ICE连接状态变更:', peerConnection.iceConnectionState);
        
        // 如果连接失败，关闭并移除该连接
        if (peerConnection.iceConnectionState === 'failed' || 
            peerConnection.iceConnectionState === 'closed' ||
            peerConnection.iceConnectionState === 'disconnected') {
          console.log('与观众的连接断开或失败:', viewerId);
          handleViewerLeave(viewerId);
        }
      };
      
      // 创建offer
      console.log('为观众创建offer:', viewerId);
      const offer = await peerConnection.createOffer({
        offerToReceiveAudio: false,
        offerToReceiveVideo: false
      });
      
      console.log('设置本地描述...');
      await peerConnection.setLocalDescription(offer);
      
      // 发送offer给观众
      if (wsRef.current?.readyState === WebSocket.OPEN) {
        console.log('发送offer到观众:', viewerId);
        wsRef.current.send(JSON.stringify({
          type: 'offer',
          data: offer,
          to: viewerId
        }));
      } else {
        console.error('WebSocket未连接，无法发送offer');
        return;
      }
      
      // 存储连接
      peersRef.current.set(viewerId, peerConnection);
      setViewerCount(prev => prev + 1);
      onViewerCountChange?.(viewerCount + 1);
      
    } catch (error) {
      console.error('处理观众加入失败:', error);
    }
  };

  // 处理answer
  const handleAnswer = async (answer, viewerId) => {
    const peerConnection = peersRef.current.get(viewerId);
    if (peerConnection) {
      try {
        console.log('设置远程描述(answer)...');
        await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
        console.log('已设置远程描述，连接建立');
      } catch (error) {
        console.error('设置远程描述失败:', error);
      }
    } else {
      console.warn('没有找到观众的PeerConnection:', viewerId);
    }
  };

  // 处理ICE候选
  const handleIceCandidate = async (candidate, viewerId) => {
    const peerConnection = peersRef.current.get(viewerId);
    if (peerConnection) {
      try {
        console.log('添加ICE候选...');
        await peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
      } catch (error) {
        console.error('添加ICE候选失败:', error);
      }
    } else {
      console.warn('没有找到观众的PeerConnection:', viewerId);
    }
  };

  // 处理观众离开
  const handleViewerLeave = (viewerId) => {
    const peerConnection = peersRef.current.get(viewerId);
    if (peerConnection) {
      console.log('关闭与观众的连接:', viewerId);
      peerConnection.close();
      peersRef.current.delete(viewerId);
      setViewerCount(prev => Math.max(0, prev - 1));
      onViewerCountChange?.(Math.max(0, viewerCount - 1));
    }
  };

  // 开始屏幕捕获
  const startCapture = async () => {
    try {
      console.log('开始捕获屏幕...');
      
      // 检查浏览器兼容性
      if (!navigator.mediaDevices) {
        throw new Error('浏览器不支持 mediaDevices API');
      }
      
      if (!navigator.mediaDevices.getDisplayMedia) {
        throw new Error('浏览器不支持屏幕共享功能，请使用Chrome、Firefox或Edge浏览器');
      }
      
      // 检查是否在HTTPS环境下（某些浏览器要求）
      if (location.protocol !== 'https:' && location.hostname !== 'localhost' && location.hostname !== '127.0.0.1') {
        console.warn('屏幕共享功能在非HTTPS环境下可能不可用');
      }
      
      // 先尝试获取麦克风权限
      let audioStream = null;
      try {
        audioStream = await navigator.mediaDevices.getUserMedia({
          audio: {
            echoCancellation: true,
            noiseSuppression: true,
            autoGainControl: true
          }
        });
        console.log('麦克风权限获取成功:', audioStream.getAudioTracks().length);
      } catch (audioErr) {
        console.warn('无法获取麦克风权限:', audioErr);
      }
      
      // 捕获屏幕
      console.log('请求屏幕共享权限...');
      const displayStream = await navigator.mediaDevices.getDisplayMedia({
        video: { 
          cursor: 'always',
          frameRate: 30,
          width: { ideal: 1920 },
          height: { ideal: 1080 }
        },
        audio: true
      });
      
      console.log('屏幕共享权限获取成功');
      
      // 合并音频轨道
      let combinedStream = displayStream;
      
      // 如果屏幕没有音频，但麦克风有音频，则添加麦克风音频
      if (displayStream.getAudioTracks().length === 0 && audioStream && audioStream.getAudioTracks().length > 0) {
        console.log('屏幕没有音频，添加麦克风音频');
        const tracks = [...displayStream.getTracks(), ...audioStream.getAudioTracks()];
        combinedStream = new MediaStream(tracks);
      }
      
      // 输出流信息
      const videoTrack = combinedStream.getVideoTracks()[0];
      const audioTracks = combinedStream.getAudioTracks();
      
      let trackInfo = `视频: ${videoTrack ? videoTrack.label : '无'}`;
      if (audioTracks.length > 0) {
        trackInfo += `, 音频: ${audioTracks.map(t => t.label).join(', ')}`;
      } else {
        trackInfo += ', 无音频';
      }
      
      setMediaInfo(trackInfo);
      console.log('媒体流信息:', trackInfo);
      
      // 同时更新state和ref
      setStream(combinedStream);
      streamRef.current = combinedStream;
      
      // 监听屏幕共享结束
      combinedStream.getVideoTracks()[0].onended = () => {
        console.log('屏幕共享已结束');
        stopStreaming();
      };
      
    } catch (err) {
      console.error('捕获失败:', err);
      
      // 提供更详细的错误信息
      let errorMessage = '捕获失败: ';
      if (err.name === 'NotAllowedError') {
        errorMessage += '用户拒绝了屏幕共享权限，请允许屏幕共享后重试';
      } else if (err.name === 'NotSupportedError') {
        errorMessage += '浏览器不支持屏幕共享功能，请使用Chrome、Firefox或Edge浏览器';
      } else if (err.name === 'NotFoundError') {
        errorMessage += '没有找到可用的屏幕或窗口';
      } else if (err.name === 'AbortError') {
        errorMessage += '用户取消了屏幕共享选择';
      } else {
        errorMessage += err.message || '未知错误';
      }
      
      setError(errorMessage);
    }
  };

  // 摄像头直播
  const startCamera = async () => {
    try {
      console.log('开始获取摄像头权限...');
      
      // 检查浏览器兼容性
      if (!navigator.mediaDevices) {
        throw new Error('浏览器不支持 mediaDevices API');
      }
      
      if (!navigator.mediaDevices.getUserMedia) {
        throw new Error('浏览器不支持摄像头功能');
      }
      
      const camStream = await navigator.mediaDevices.getUserMedia({ 
        video: {
          width: { ideal: 1280 },
          height: { ideal: 720 },
          frameRate: { ideal: 30 }
        }, 
        audio: false 
      });
      
      console.log('摄像头权限获取成功，轨道数量:', camStream.getTracks().length);
      setCameraStream(camStream);
      setMediaInfo('摄像头已连接');
      
      // 为所有已连接的观众重新发送包含摄像头流的offer
      console.log('开始为已连接观众更新摄像头流...');
      await updateAllViewersWithCamera(camStream);
    } catch (err) {
      console.error('获取摄像头权限失败:', err);
      
      // 提供更详细的错误信息
      let errorMessage = '无法获取摄像头权限: ';
      if (err.name === 'NotAllowedError') {
        errorMessage += '用户拒绝了摄像头权限，请在浏览器设置中允许摄像头访问';
      } else if (err.name === 'NotFoundError') {
        errorMessage += '没有找到可用的摄像头设备';
      } else if (err.name === 'NotSupportedError') {
        errorMessage += '浏览器不支持摄像头功能';
      } else if (err.name === 'NotReadableError') {
        errorMessage += '摄像头被其他应用程序占用，请关闭其他使用摄像头的应用';
      } else {
        errorMessage += err.message || '未知错误';
      }
      
      setError(errorMessage);
    }
  };

  // 为所有已连接的观众更新摄像头流
  const updateAllViewersWithCamera = async (newCameraStream) => {
    if (peersRef.current.size === 0) {
      console.log('没有已连接的观众，无需更新摄像头流');
      return;
    }

    console.log(`为${peersRef.current.size}个已连接的观众更新摄像头流`);
    
    for (const [viewerId, peerConnection] of peersRef.current) {
      try {
        // 移除旧的摄像头轨道（如果存在）
        const senders = peerConnection.getSenders();
        const cameraSender = senders.find(sender => 
          sender.track && (sender.track.contentHint === 'camera' || sender.track._isCameraTrack === true)
        );
        
        if (cameraSender) {
          await peerConnection.removeTrack(cameraSender);
          console.log('移除旧的摄像头轨道');
        }
        
        // 添加新的摄像头轨道
        const cameraTracks = newCameraStream.getTracks();
        cameraTracks.forEach(track => {
          track.contentHint = 'camera';
          peerConnection.addTrack(track, newCameraStream);
          console.log('添加新的摄像头轨道:', track.kind, track.id);
        });
        
        // 创建新的offer
        const offer = await peerConnection.createOffer();
        await peerConnection.setLocalDescription(offer);
        
        // 发送新的offer
        if (wsRef.current?.readyState === WebSocket.OPEN) {
          wsRef.current.send(JSON.stringify({
            type: 'offer',
            data: offer,
            to: viewerId
          }));
          console.log('发送包含摄像头流的新offer给观众:', viewerId);
        }
      } catch (error) {
        console.error('更新观众摄像头流失败:', viewerId, error);
      }
    }
  };

  // 停止摄像头
  const stopCamera = async () => {
    if (cameraStream) {
      console.log('开始停止摄像头...');
      // 停止所有摄像头轨道
      cameraStream.getTracks().forEach(track => {
        console.log('停止摄像头轨道:', track.id, track.label);
        track.stop();
      });
      setCameraStream(null);
      setMediaInfo('摄像头已断开');
      
      // 为所有已连接的观众移除摄像头流
      console.log('开始为观众移除摄像头流...');
      await removeCameraFromAllViewers();
    }
  };

  // 为所有已连接的观众移除摄像头流
  const removeCameraFromAllViewers = async () => {
    if (peersRef.current.size === 0) {
      console.log('没有已连接的观众，无需移除摄像头流');
      return;
    }

    console.log(`为${peersRef.current.size}个已连接的观众移除摄像头流`);
    
    for (const [viewerId, peerConnection] of peersRef.current) {
      try {
        // 移除摄像头轨道
        const senders = peerConnection.getSenders();
        const cameraSender = senders.find(sender => 
          sender.track && (sender.track.contentHint === 'camera' || sender.track._isCameraTrack === true)
        );
        
        if (cameraSender) {
          await peerConnection.removeTrack(cameraSender);
          console.log('移除摄像头轨道');
          
          // 创建新的offer
          const offer = await peerConnection.createOffer();
          await peerConnection.setLocalDescription(offer);
          
          // 发送新的offer
          if (wsRef.current?.readyState === WebSocket.OPEN) {
            wsRef.current.send(JSON.stringify({
              type: 'offer',
              data: offer,
              to: viewerId
            }));
            console.log('发送移除摄像头流的新offer给观众:', viewerId);
          }
        }
      } catch (error) {
        console.error('移除观众摄像头流失败:', viewerId, error);
      }
    }
  };

  // 拖拽事件
  const onMouseDown = (e) => {
    setDragging(true);
    setDragOffset({
      x: e.clientX - pipPos.left,
      y: e.clientY - pipPos.top,
    });
  };
  const onMouseMove = (e) => {
    if (dragging) {
      setPipPos({
        left: e.clientX - dragOffset.x,
        top: e.clientY - dragOffset.y,
      });
    }
  };
  const onMouseUp = () => setDragging(false);

  // 弹幕画中画拖拽事件
  const onDanmakuPipMouseDown = (e) => {
    setDanmakuDragging(true);
    setDanmakuDragOffset({
      x: e.clientX - danmakuPipPos.left,
      y: e.clientY - danmakuPipPos.top,
    });
  };
  const onDanmakuPipMouseMove = (e) => {
    if (danmakuDragging) {
      setDanmakuPipPos({
        left: e.clientX - danmakuDragOffset.x,
        top: e.clientY - danmakuDragOffset.y,
      });
    }
  };
  const onDanmakuPipMouseUp = () => setDanmakuDragging(false);

  // 投票画中画拖拽事件
  const onVotePipMouseDown = (e) => {
    setVoteDragging(true);
    setVoteDragOffset({
      x: e.clientX - votePipPos.left,
      y: e.clientY - votePipPos.top,
    });
  };
  const onVotePipMouseMove = (e) => {
    if (voteDragging) {
      setVotePipPos({
        left: e.clientX - voteDragOffset.x,
        top: e.clientY - voteDragOffset.y,
      });
    }
  };
  const onVotePipMouseUp = () => setVoteDragging(false);

  // 弹幕相关函数
  const addDanmakuMessage = (message) => {
    console.log('主播端添加弹幕消息:', message);
    console.log('当前弹幕数量:', danmakuMessages.length);
    
    const currentTime = Date.now();
    
    // 智能选择可用轨道
    const findAvailableTrack = () => {
      const now = currentTime;
      for (let i = 0; i < 8; i++) {
        if (trackOccupancy[i] <= now) {
          return i;
        }
      }
      // 如果所有轨道都被占用，选择最早释放的轨道
      return trackOccupancy.indexOf(Math.min(...trackOccupancy));
    };
    
    const selectedTrack = findAvailableTrack();
    const speed = ['speed-slow', 'speed-normal', 'speed-fast'][Math.floor(Math.random() * 3)];
    const duration = speed === 'speed-fast' ? 9000 : speed === 'speed-slow' ? 15000 : 12000;
    
    // 为弹幕添加随机样式属性
    const enhancedMessage = {
      ...message,
      track: selectedTrack,
      speed: speed,
      size: Math.random() > 0.85 ? 'size-large' : Math.random() > 0.7 ? 'size-small' : '',
      delay: Math.random() * 1, // 随机延迟0-1秒
    };
    
    console.log('主播端增强后的弹幕消息:', enhancedMessage);
    
    // 更新轨道占用时间
    setTrackOccupancy(prev => {
      const newOccupancy = [...prev];
      newOccupancy[selectedTrack] = currentTime + duration + (enhancedMessage.delay * 1000);
      return newOccupancy;
    });
    
    setDanmakuMessages(prev => {
      const newMessages = [...prev, enhancedMessage];
      console.log('主播端更新弹幕列表，新数量:', newMessages.length);
      return newMessages;
    });
    
    // 自动清理过期弹幕（保持最多50条）
    setTimeout(() => {
      setDanmakuMessages(prev => prev.filter(msg => msg.id !== enhancedMessage.id));
    }, duration + 2000);
  };

  const clearDanmaku = () => {
    setDanmakuMessages([]);
  };

  const broadcastDanmaku = (message) => {
    // 广播弹幕给所有观众
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      console.log('广播弹幕给所有观众:', message);
      wsRef.current.send(JSON.stringify({
        type: 'broadcast-danmaku',
        data: message,
        roomId
      }));
    }
  };

  // 签到相关函数
  const getCheckInStats = () => {
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({
        type: 'get-checkin-stats',
        roomId
      }));
    }
  };

  const resetCheckIn = () => {
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({
        type: 'reset-checkin',
        roomId
      }));
    }
  };

  // 投票系统相关函数
  const startVote = () => {
    const question = prompt('请输入投票问题:');
    if (!question) return;
    
    const optionsInput = prompt('请输入选项，用逗号分隔（例如：选项A,选项B,选项C）:');
    if (!optionsInput) return;
    
    const options = optionsInput.split(',').map(opt => opt.trim()).filter(opt => opt);
    if (options.length < 2) {
      alert('至少需要2个选项');
      return;
    }
    
    console.log('准备发送投票开始消息:', {
      type: 'start-vote',
      question,
      options,
      roomId,
      wsState: wsRef.current?.readyState
    });
    
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      const message = {
        type: 'start-vote',
        data: {
          question,
          options
        },
        roomId
      };
      console.log('发送投票开始消息:', message);
      wsRef.current.send(JSON.stringify(message));
    } else {
      console.error('WebSocket未连接，无法发送投票消息');
      alert('WebSocket未连接，请先开始直播');
    }
  };

  const endVote = () => {
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({
        type: 'end-vote',
        roomId
      }));
    }
  };

  const resetVote = () => {
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({
        type: 'reset-vote',
        roomId
      }));
    }
  };

  const getVoteStats = () => {
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify({
        type: 'get-vote-stats',
        roomId
      }));
    }
  };

  useEffect(() => {
    if (dragging) {
      window.addEventListener('mousemove', onMouseMove);
      window.addEventListener('mouseup', onMouseUp);
    } else {
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mouseup', onMouseUp);
    }
    return () => {
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mouseup', onMouseUp);
    };
  }, [dragging]);

  // 弹幕画中画拖拽监听
  useEffect(() => {
    if (danmakuDragging) {
      window.addEventListener('mousemove', onDanmakuPipMouseMove);
      window.addEventListener('mouseup', onDanmakuPipMouseUp);
    } else {
      window.removeEventListener('mousemove', onDanmakuPipMouseMove);
      window.removeEventListener('mouseup', onDanmakuPipMouseUp);
    }
    return () => {
      window.removeEventListener('mousemove', onDanmakuPipMouseMove);
      window.removeEventListener('mouseup', onDanmakuPipMouseUp);
    };
  }, [danmakuDragging]);

  // 投票画中画拖拽监听
  useEffect(() => {
    if (voteDragging) {
      window.addEventListener('mousemove', onVotePipMouseMove);
      window.addEventListener('mouseup', onVotePipMouseUp);
    } else {
      window.removeEventListener('mousemove', onVotePipMouseMove);
      window.removeEventListener('mouseup', onVotePipMouseUp);
    }
    return () => {
      window.removeEventListener('mousemove', onVotePipMouseMove);
      window.removeEventListener('mouseup', onVotePipMouseUp);
    };
  }, [voteDragging]);

  useEffect(() => {
    if (cameraStream && cameraVideoRef.current) {
      cameraVideoRef.current.srcObject = cameraStream;
    }
  }, [cameraStream]);

  useEffect(() => {
    if (stream && videoRef.current) {
      console.log('设置本地视频预览...');
      videoRef.current.srcObject = stream;
    }
  }, [stream]);

  // 监听全屏状态变化
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };
    
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
    };
  }, []);

  // 开始直播
  const startStreaming = () => {
    if (!streamRef.current) {
      console.error('没有媒体流，无法开始直播');
      setError('请先开始捕获屏幕');
      return;
    }
    
    console.log('开始直播...');
    setIsStreaming(true);
    
    // 确保WebSocket已连接
    if (wsRef.current?.readyState !== WebSocket.OPEN) {
      console.log('WebSocket未连接，重新连接...');
      connectWebSocket();
    }
    
    // 通知服务器开始直播
    setTimeout(() => {
      if (wsRef.current?.readyState === WebSocket.OPEN) {
        console.log('通知服务器开始直播');
        wsRef.current.send(JSON.stringify({
          type: 'start-streaming',
          roomId
        }));
      } else {
        console.error('WebSocket未连接，无法开始直播');
        setError('WebSocket未连接，无法开始直播');
      }
    }, 1000);

    // ====== 新增全屏逻辑 ======
    if (previewRef.current && previewRef.current.requestFullscreen) {
      previewRef.current.requestFullscreen();
    }
    // =========================
  };

    // 停止直播
  const stopStreaming = () => {
    console.log('停止直播...');
    
    // 关闭所有peer连接
    peersRef.current.forEach((pc, viewerId) => {
      console.log('关闭与观众的连接:', viewerId);
      pc.close();
    });
    peersRef.current.clear();
    
    // 停止媒体流
    if (streamRef.current) {
      console.log('停止所有媒体轨道');
      streamRef.current.getTracks().forEach(track => track.stop());
      streamRef.current = null;
      setStream(null);
    }
    
    // 停止摄像头流
    if (cameraStream) {
      console.log('停止摄像头轨道');
      cameraStream.getTracks().forEach(track => track.stop());
      setCameraStream(null);
    }
    
    // 关闭WebSocket
    if (wsRef.current) {
      console.log('关闭WebSocket连接');
      wsRef.current.close();
      wsRef.current = null;
    }
    
    setIsStreaming(false);
    setError(null);
    setMediaInfo('');
    setViewerCount(0);
    setConnectionStatus('disconnected');
    onViewerCountChange?.(0);
  };

  // 组件卸载时清理
  useEffect(() => {
    // 组件加载时立即连接WebSocket
    console.log('直播端组件加载，连接WebSocket...');
    connectWebSocket();
    
    // 获取签到统计
    setTimeout(() => {
      getCheckInStats();
    }, 2000);
    
    return () => {
      stopStreaming();
    };
  }, []);

  return (
    <div className={styles.app}>
      {/* 头部导航 */}
      <div className={styles.chatHeader}>
        <button 
          className={styles.backButton}
          onClick={goToHome}
          title="返回首页"
        >
          ← 返回
        </button>
        <div className={styles.headerInfo}>
          <h1 className={styles.chatTitle}>📺 直播发送端</h1>
          <p className={styles.roomInfo}>主播房间: {roomId}</p>
        </div>
      </div>
      
      {/* 主要内容区域 */}
      <div className={styles.mainContent}>
        <div className={styles.streamContainer}>
          <div className={styles.header}>
            <h2 className={styles.title}>直播控制台</h2>
            <div className={styles.status}>
              <span className={`${styles.statusDot} ${styles[connectionStatus]}`}></span>
              <span>观众: {viewerCount}</span>
              <span style={{ marginLeft: '10px', fontSize: '12px' }}>
                WebSocket: {wsRef.current?.readyState === WebSocket.OPEN ? '已连接' : '未连接'}
              </span>
            </div>
          </div>
          
          {error && <div className={styles.error}>{error}</div>}
          {mediaInfo && <div className={styles.mediaInfo}>{mediaInfo}</div>}
          
          {/* 浏览器兼容性信息 */}
          {!browserSupport.mediaDevices && (
            <div className={styles.error}>
              ⚠️ 浏览器兼容性问题：不支持 mediaDevices API，请使用Chrome、Firefox或Edge浏览器
            </div>
          )}
          {browserSupport.mediaDevices && !browserSupport.getDisplayMedia && (
            <div className={styles.error}>
              ⚠️ 浏览器兼容性问题：不支持屏幕共享功能，请使用Chrome、Firefox或Edge浏览器
            </div>
          )}
          {browserSupport.mediaDevices && browserSupport.getDisplayMedia && !window.isSecureContext && 
           location.hostname !== 'localhost' && location.hostname !== '127.0.0.1' && (
            <div className={styles.error}>
              ⚠️ 安全环境问题：媒体API需要HTTPS环境
              <br />
              <strong>解决方案：</strong>
              <br />
              1. Chrome: 在地址栏输入 chrome://flags/ → 搜索"Insecure origins" → 添加 http://192.168.8.41:5173
              <br />
              2. Firefox: 在地址栏输入 about:config → 搜索"media.devices.insecure.enabled" → 设置为 true
              <br />
              3. 或者使用 localhost 访问：http://localhost:5173
            </div>
          )}
          
                      {/* 弹幕统计信息 */}
            {isStreaming && (
              <div className={styles.mediaInfo}>
                💬 弹幕: {danmakuMessages.length} 条 | 观众: {viewerCount} 人 | ✅ 签到: {checkInCount} 人 | 🗳️ 投票: {voteData.totalVotes} 票
              </div>
            )}

          <div className={styles.controls}>
            {/* 直播控制菜单 */}
            <DropdownMenu 
              title="📺 直播控制" 
              isOpen={openMenus.stream} 
              onToggle={() => toggleMenu('stream')}
            >
              <div className={styles.buttonGroup}>
                <button 
                  className={styles.button} 
                  onClick={startCapture} 
                  disabled={stream || !browserSupport.getDisplayMedia}
                >
                  开始捕获
                </button>
                <button 
                  className={styles.button} 
                  onClick={startCamera}
                  disabled={cameraStream || !browserSupport.getUserMedia}
                >
                  开启摄像头
                </button>
                <button 
                  className={styles.button} 
                  onClick={stopCamera}
                  disabled={!cameraStream}
                >
                  关闭摄像头
                </button>
                <button 
                  className={styles.button} 
                  onClick={startStreaming} 
                  disabled={!stream || isStreaming}
                  style={{ backgroundColor: '#4CAF50', color: 'white' }}
                >
                  开始直播
                </button>
                <button 
                  className={styles.button} 
                  onClick={stopStreaming} 
                  disabled={!isStreaming}
                  style={{ backgroundColor: '#f44336', color: 'white' }}
                >
                  停止直播
                </button>
              </div>
            </DropdownMenu>

            {/* 弹幕控制菜单 */}
            <DropdownMenu 
              title="💬 弹幕控制" 
              isOpen={openMenus.danmaku} 
              onToggle={() => toggleMenu('danmaku')}
            >
              <div className={styles.buttonGroup}>
                <button 
                  className={styles.button} 
                  onClick={() => setDanmakuEnabled(!danmakuEnabled)}
                  style={{ 
                    backgroundColor: danmakuEnabled ? '#4CAF50' : '#f44336',
                    color: 'white'
                  }}
                >
                  {danmakuEnabled ? '弹幕开' : '弹幕关'}
                </button>
                <button 
                  className={styles.button} 
                  onClick={clearDanmaku}
                  style={{ backgroundColor: '#ff9800', color: 'white' }}
                >
                  清空弹幕
                </button>
                <button 
                  className={styles.button} 
                  onClick={() => setShowDanmakuPip(!showDanmakuPip)}
                  style={{ 
                    backgroundColor: showDanmakuPip ? '#2196F3' : '#9E9E9E',
                    color: 'white'
                  }}
                >
                  {showDanmakuPip ? '隐藏弹幕窗口' : '显示弹幕窗口'}
                </button>
              </div>
            </DropdownMenu>

            {/* 签到控制菜单 */}
            <DropdownMenu 
              title="✅ 签到控制" 
              isOpen={openMenus.checkin} 
              onToggle={() => toggleMenu('checkin')}
            >
              <div className={styles.buttonGroup}>
                <button 
                  className={styles.button} 
                  onClick={getCheckInStats}
                  style={{ backgroundColor: '#9C27B0', color: 'white' }}
                >
                  刷新签到
                </button>
                <button 
                  className={styles.button} 
                  onClick={resetCheckIn}
                  style={{ backgroundColor: '#FF5722', color: 'white' }}
                >
                  重置签到
                </button>
                <button 
                  className={styles.button} 
                  onClick={() => setShowCheckInPip(!showCheckInPip)}
                  style={{ 
                    backgroundColor: showCheckInPip ? '#4CAF50' : '#9E9E9E',
                    color: 'white'
                  }}
                >
                  {showCheckInPip ? '隐藏签到窗口' : '显示签到窗口'}
                </button>
              </div>
            </DropdownMenu>

            {/* 投票控制菜单 */}
            <DropdownMenu 
              title="🗳️ 投票控制" 
              isOpen={openMenus.vote} 
              onToggle={() => toggleMenu('vote')}
            >
              <div className={styles.buttonGroup}>
                <button 
                  className={styles.button} 
                  onClick={startVote}
                  disabled={voteData.isActive}
                  style={{ 
                    backgroundColor: voteData.isActive ? '#9E9E9E' : '#E91E63', 
                    color: 'white' 
                  }}
                >
                  {voteData.isActive ? '投票进行中' : '开始投票'}
                </button>
                <button 
                  className={styles.button} 
                  onClick={endVote}
                  disabled={!voteData.isActive}
                  style={{ 
                    backgroundColor: !voteData.isActive ? '#9E9E9E' : '#FF5722', 
                    color: 'white' 
                  }}
                >
                  结束投票
                </button>
                <button 
                  className={styles.button} 
                  onClick={resetVote}
                  style={{ backgroundColor: '#795548', color: 'white' }}
                >
                  重置投票
                </button>
                <button 
                  className={styles.button} 
                  onClick={() => setShowVotePip(!showVotePip)}
                  style={{ 
                    backgroundColor: showVotePip ? '#4CAF50' : '#9E9E9E',
                    color: 'white'
                  }}
                >
                  {showVotePip ? '隐藏投票窗口' : '显示投票窗口'}
                </button>
              </div>
            </DropdownMenu>
          </div>

          <div className={styles.preview} ref={previewRef} style={{ position: 'relative' }}>
            {stream ? (
              <video 
                ref={videoRef} 
                autoPlay 
                muted 
                playsInline
                controls={false}
                className={styles.video}
                onError={(e) => console.error('视频错误:', e)}
              />
            ) : (
              <div className={styles.placeholder}>点击"开始捕获"按钮选择屏幕区域</div>
            )}
            
            {/* 摄像头画中画小窗口 */}
            {cameraStream && (
              <video
                ref={cameraVideoRef}
                autoPlay
                muted
                style={{
                  position: 'absolute',
                  width: 180,
                  height: 120,
                  left: pipPos.left,
                  top: pipPos.top,
                  borderRadius: 12,
                  border: '2px solid #fff',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.3)',
                  cursor: 'move',
                  zIndex: 10,
                }}
                onMouseDown={onMouseDown}
              />
            )}
            
            {/* 弹幕画中画小窗口 */}
            {showDanmakuPip && danmakuEnabled && (
              <div
                style={{
                  position: 'absolute',
                  width: 300,
                  height: 200,
                  left: danmakuPipPos.left,
                  top: danmakuPipPos.top,
                  borderRadius: 12,
                  border: '2px solid #4CAF50',
                  backgroundColor: 'rgba(0, 0, 0, 0.8)',
                  boxShadow: '0 4px 16px rgba(76, 175, 80, 0.4)',
                  cursor: 'move',
                  zIndex: 15,
                  overflow: 'hidden',
                  backdropFilter: 'blur(4px)'
                }}
                onMouseDown={onDanmakuPipMouseDown}
              >
                {/* 弹幕窗口标题栏 */}
                <div style={{
                  background: 'linear-gradient(90deg, #4CAF50, #66BB6A)',
                  color: 'white',
                  padding: '8px 12px',
                  fontSize: '12px',
                  fontWeight: 'bold',
                  borderTopLeftRadius: '10px',
                  borderTopRightRadius: '10px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <span>💬 观众弹幕</span>
                  <span style={{ fontSize: '10px' }}>{danmakuMessages.length} 条</span>
                </div>
                
                {/* 弹幕显示区域 */}
                <div style={{
                  height: 'calc(100% - 32px)',
                  overflow: 'hidden',
                  position: 'relative',
                  padding: '8px'
                }}>
                  {danmakuMessages.slice(-10).map((msg, index) => (
                    <div 
                      key={`pip-${msg.id}-${index}-${msg.timestamp}`}
                      style={{
                        background: msg.sender === 'viewer' ? 'linear-gradient(90deg, #4CAF50, #66BB6A)' : 'linear-gradient(90deg, #FF9800, #FFB74D)',
                        color: 'white',
                        padding: '4px 8px',
                        borderRadius: '8px',
                        fontSize: '11px',
                        marginBottom: '4px',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis',
                        maxWidth: '100%',
                        boxShadow: '0 1px 3px rgba(0,0,0,0.3)',
                        animation: 'fadeInUp 0.3s ease'
                      }}
                    >
                      {msg.sender === 'viewer' ? '观众: ' : '系统: '}{msg.content}
                    </div>
                  ))}
                  
                  {/* 空状态 */}
                  {danmakuMessages.length === 0 && (
                    <div style={{
                      color: '#ccc',
                      fontSize: '12px',
                      textAlign: 'center',
                      marginTop: '60px'
                    }}>
                      等待观众发送弹幕...
                    </div>
                  )}
                </div>
              </div>
            )}
            
            {/* 签到画中画小窗口 */}
            {showCheckInPip && (
              <div
                style={{
                  position: 'absolute',
                  width: 300,
                  height: 200,
                  left: danmakuPipPos.left + 320,
                  top: danmakuPipPos.top,
                  borderRadius: 12,
                  border: '2px solid #9C27B0',
                  backgroundColor: 'rgba(0, 0, 0, 0.8)',
                  boxShadow: '0 4px 16px rgba(156, 39, 176, 0.4)',
                  cursor: 'move',
                  zIndex: 15,
                  overflow: 'hidden',
                  backdropFilter: 'blur(4px)'
                }}
              >
                {/* 签到窗口标题栏 */}
                <div style={{
                  background: 'linear-gradient(90deg, #9C27B0, #BA68C8)',
                  color: 'white',
                  padding: '8px 12px',
                  fontSize: '12px',
                  fontWeight: 'bold',
                  borderTopLeftRadius: '10px',
                  borderTopRightRadius: '10px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <span>✅ 观众签到</span>
                  <span style={{ fontSize: '10px' }}>{checkInCount} 人</span>
                </div>
                
                {/* 签到显示区域 */}
                <div style={{
                  height: 'calc(100% - 32px)',
                  overflow: 'hidden',
                  position: 'relative',
                  padding: '8px'
                }}>
                  {checkInCount > 0 ? (
                    <div style={{
                      color: '#fff',
                      fontSize: '11px',
                      lineHeight: '1.4'
                    }}>
                      <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>
                        签到人数: {checkInCount}
                      </div>
                      <div style={{ fontSize: '10px', opacity: 0.8 }}>
                        最近签到用户:
                      </div>
                      {Array.from(checkInUsers).slice(-5).map((userId, index) => (
                        <div key={userId} style={{
                          background: 'rgba(156, 39, 176, 0.3)',
                          padding: '2px 6px',
                          margin: '2px 0',
                          borderRadius: '4px',
                          fontSize: '9px'
                        }}>
                          {userId.substring(0, 8)}...
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div style={{
                      color: '#ccc',
                      fontSize: '12px',
                      textAlign: 'center',
                      marginTop: '60px'
                    }}>
                      等待观众签到...
                    </div>
                  )}
                </div>
              </div>
            )}
            
            {/* 投票画中画小窗口 */}
            {showVotePip && (
              <div
                style={{
                  position: 'absolute',
                  width: 350,
                  height: 250,
                  left: votePipPos.left,
                  top: votePipPos.top,
                  borderRadius: 12,
                  border: '2px solid #E91E63',
                  backgroundColor: 'rgba(0, 0, 0, 0.8)',
                  boxShadow: '0 4px 16px rgba(233, 30, 99, 0.4)',
                  cursor: 'move',
                  zIndex: 15,
                  overflow: 'hidden',
                  backdropFilter: 'blur(4px)'
                }}
                onMouseDown={onVotePipMouseDown}
              >
                {/* 投票窗口标题栏 */}
                <div style={{
                  background: 'linear-gradient(90deg, #E91E63, #F06292)',
                  color: 'white',
                  padding: '8px 12px',
                  fontSize: '12px',
                  fontWeight: 'bold',
                  borderTopLeftRadius: '10px',
                  borderTopRightRadius: '10px',
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <span>🗳️ 投票系统</span>
                  <span style={{ fontSize: '10px' }}>
                    {voteData.isActive ? '进行中' : '未开始'} | {voteData.totalVotes} 票
                  </span>
                </div>
                
                {/* 投票显示区域 */}
                <div style={{
                  height: 'calc(100% - 32px)',
                  overflow: 'hidden',
                  position: 'relative',
                  padding: '8px'
                }}>
                  {voteData.isActive ? (
                    <div style={{
                      color: '#fff',
                      fontSize: '11px',
                      lineHeight: '1.4'
                    }}>
                      <div style={{ marginBottom: '8px', fontWeight: 'bold', fontSize: '12px' }}>
                        {voteData.question}
                      </div>
                      <div style={{ fontSize: '10px', opacity: '0.8', marginBottom: '8px' }}>
                        选项:
                      </div>
                      {voteData.options.map((option, index) => {
                        const votes = voteData.results[index] || 0;
                        const percentage = voteData.totalVotes > 0 ? (votes / voteData.totalVotes * 100).toFixed(1) : 0;
                        return (
                          <div key={index} style={{
                            marginBottom: '6px',
                            background: 'rgba(233, 30, 99, 0.2)',
                            borderRadius: '6px',
                            padding: '4px 8px'
                          }}>
                            <div style={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              marginBottom: '2px'
                            }}>
                              <span style={{ fontSize: '10px' }}>{option}</span>
                              <span style={{ fontSize: '9px', opacity: '0.8' }}>{votes} 票</span>
                            </div>
                            <div style={{
                              width: '100%',
                              height: '4px',
                              background: 'rgba(255,255,255,0.2)',
                              borderRadius: '2px',
                              overflow: 'hidden'
                            }}>
                              <div style={{
                                width: `${percentage}%`,
                                height: '100%',
                                background: 'linear-gradient(90deg, #E91E63, #F06292)',
                                borderRadius: '2px',
                                transition: 'width 0.3s ease'
                              }} />
                            </div>
                            <div style={{
                              fontSize: '8px',
                              opacity: '0.7',
                              textAlign: 'right'
                            }}>
                              {percentage}%
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  ) : voteData.totalVotes > 0 ? (
                    <div style={{
                      color: '#fff',
                      fontSize: '11px',
                      lineHeight: '1.4'
                    }}>
                      <div style={{ marginBottom: '8px', fontWeight: 'bold', fontSize: '12px' }}>
                        投票结果
                      </div>
                      <div style={{ fontSize: '10px', opacity: '0.8', marginBottom: '8px' }}>
                        总票数: {voteData.totalVotes}
                      </div>
                      {voteData.options.map((option, index) => {
                        const votes = voteData.results[index] || 0;
                        const percentage = voteData.totalVotes > 0 ? (votes / voteData.totalVotes * 100).toFixed(1) : 0;
                        return (
                          <div key={index} style={{
                            marginBottom: '6px',
                            background: 'rgba(233, 30, 99, 0.2)',
                            borderRadius: '6px',
                            padding: '4px 8px'
                          }}>
                            <div style={{
                              display: 'flex',
                              justifyContent: 'space-between',
                              alignItems: 'center',
                              marginBottom: '2px'
                            }}>
                              <span style={{ fontSize: '10px' }}>{option}</span>
                              <span style={{ fontSize: '9px', opacity: '0.8' }}>{votes} 票</span>
                            </div>
                            <div style={{
                              width: '100%',
                              height: '4px',
                              background: 'rgba(255,255,255,0.2)',
                              borderRadius: '2px',
                              overflow: 'hidden'
                            }}>
                              <div style={{
                                width: `${percentage}%`,
                                height: '100%',
                                background: 'linear-gradient(90deg, #E91E63, #F06292)',
                                borderRadius: '2px'
                              }} />
                            </div>
                            <div style={{
                              fontSize: '8px',
                              opacity: '0.7',
                              textAlign: 'right'
                            }}>
                              {percentage}%
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  ) : (
                    <div style={{
                      color: '#ccc',
                      fontSize: '12px',
                      textAlign: 'center',
                      marginTop: '80px'
                    }}>
                      等待开始投票...
                    </div>
                  )}
                </div>
              </div>
            )}
            
            {/* 弹幕显示区域 - 移到外部，确保始终显示 */}
            {danmakuEnabled && (
              <div className={styles.danmakuDisplay}>
                {/* 调试信息 */}
                <div style={{ 
                  position: 'absolute', 
                  top: '10px', 
                  left: '10px', 
                  background: 'rgba(0,0,0,0.7)', 
                  color: 'white', 
                  padding: '5px', 
                  borderRadius: '4px',
                  fontSize: '12px',
                  zIndex: 1000
                }}>
                  弹幕数量: {danmakuMessages.length} | 弹幕开关: {danmakuEnabled ? '开' : '关'}
                </div>
                
                {danmakuMessages.slice(-20).map((msg, index) => (
                  <div 
                    key={`main-${msg.id}-${index}-${msg.timestamp}`}
                    className={`${styles.danmakuItem} ${msg.speed ? styles[msg.speed] : ''} ${msg.size ? styles[msg.size] : ''} ${msg.sender === 'viewer' ? styles.viewerMessage : ''}`}
                    style={{
                      top: `${(msg.track || 0) * 12 + 10}%`,
                      animationDelay: `${(msg.delay || 0) + index * 0.3}s`,
                      animationDuration: msg.speed === 'speed-fast' ? '9s' : msg.speed === 'speed-slow' ? '15s' : '12s'
                    }}
                  >
                    {msg.content}
                  </div>
                ))}
              </div>
            )}
            
            {/* 可选：退出全屏按钮 */}
            {isFullscreen && (
              <button
                style={{ position: 'absolute', top: 10, right: 10, zIndex: 10 }}
                onClick={() => {
                  document.exitFullscreen().catch(err => {
                    console.error('退出全屏失败:', err);
                  });
                }}
              >退出全屏</button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default StreamSender;